﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Management;
namespace FightLand_Sever
{

    class Tools
    {
        static string localip = "";

        static Tools()
        {
            var ips = Dns.GetHostAddresses(Dns.GetHostName());
            localip = ips[ips.Length - 1].ToString();
        }

        /// <summary>
        /// 属性克隆
        /// </summary>
        public static void CloneProperty<T, V>(T tag, ref V from)
        {
            Type tagType = tag.GetType();
            Type fromType = from.GetType();
            foreach (var p in tagType.GetProperties())
            {
                foreach (var f in fromType.GetProperties())
                {
                    if (p.Name.Equals(f.Name) && p.PropertyType.FullName.Equals(f.PropertyType.FullName))
                    {
                        f.SetValue(from, p.GetValue(tag));
                    }
                }
            }
        }

        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
#if !DEBUG
            return localip;
#endif
            //return ip;
#if DEBUG
            return "127.0.0.1";
#endif
        }

        /// <summary>  
        /// 将字节转换为GB
        /// </summary>  
        /// <param name="size">字节值</param>  
        /// <param name="mod">除数，硬盘除以1000，内存除以1024</param>  
        /// <returns></returns>  
        public static string ToGB(double size, double mod)
        {
            String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
            int i = 0;
            while (size >= mod)
            {
                size /= mod;
                i++;
            }
            return Math.Round(size) + units[i];
        }

        public static class Sys
        {
            /// <summary>
            /// 内存信息
            /// </summary>
            public struct MEMORYSTATUS1
            {
                /// <summary>
                /// MEMORYSTATUS结构的大小，在调GlobalMemoryStatus函数前用sizeof()函数求得，用来供函数检测结构的版本。
                /// </summary>
                internal uint dwLength;
                /// <summary>
                /// 返回一个介于0～100之间的值，用来指示当前系统内存的使用率。
                /// </summary>
                internal uint dwMemoryLoad;
                /// <summary>
                /// 返回总的物理内存大小，以 字节 (byte)为单位。
                /// </summary>
                internal uint dwTotalPhys;
                /// <summary>
                /// 返回可用的物理内存大小，以 字节 (byte)为单位。
                /// </summary>
                internal uint dwAvailPhys;
                /// <summary>
                /// 显示可以存在 页面文件 中的字节数。注意这个数值并不表示在 页面文件 在 磁盘 上的真实物理大小。
                /// </summary>
                internal uint dwTotalPageFile;
                /// <summary>
                /// 返回可用的页面文件大小，以 字节 (byte)为单位。
                /// </summary>
                internal uint dwAvailPageFile;
                /// <summary>
                /// 返回调用进程的用户模式部分的全部可用 虚拟地址 空间，以 字节 (byte)为单位。
                /// </summary>
                internal uint dwTotalVirtual;
                /// <summary>
                /// 返回调用进程的用户模式部分的实际自由可用的 虚拟地址 空间，以 字节 (byte)为单位。
                /// </summary>
                internal uint dwAvailVirtual;
            }

            /// <summary>
            /// windows api 名称
            /// </summary>
            public enum WindowsAPIType
            {
                /// <summary>
                /// 内存
                /// </summary>
                Win32_PhysicalMemory,
                /// <summary>
                /// cpu
                /// </summary>
                Win32_Processor,
                /// <summary>
                /// 硬盘
                /// </summary>
                win32_DiskDrive,
                /// <summary>
                /// 电脑型号
                /// </summary>
                Win32_ComputerSystemProduct,
                /// <summary>
                /// 分辨率
                /// </summary>
                Win32_DesktopMonitor,
                /// <summary>
                /// 显卡
                /// </summary>
                Win32_VideoController,
                /// <summary>
                /// 操作系统
                /// </summary>
                Win32_OperatingSystem

            }

            public enum WindowsAPIKeys
            {
                /// <summary>
                /// 名称
                /// </summary>
                Name,
                /// <summary>
                /// 显卡芯片
                /// </summary>
                VideoProcessor,
                /// <summary>
                /// 显存大小
                /// </summary>
                AdapterRAM,
                /// <summary>
                /// 分辨率宽
                /// </summary>
                ScreenWidth,
                /// <summary>
                /// 分辨率高
                /// </summary>
                ScreenHeight,
                /// <summary>
                /// 电脑型号
                /// </summary>
                Version,
                /// <summary>
                /// 硬盘容量
                /// </summary>
                Size,
                /// <summary>
                /// 内存容量
                /// </summary>
                Capacity,
                /// <summary>
                /// cpu核心数
                /// </summary>
                NumberOfCores
            }

            static string cpu = "";
            static string memory = "";

            static Sys()
            {
                var cp = QueryCPU();
                cpu = string.Format("CPU:{0} {1}", cp.Item1 + " / " + cp.Item2, GetCPU_Count());
                memory = GetPhisicalMemory();
            }


            [DllImport("kernel32.dll ")]//调用系统DLL
            public static extern void GlobalMemoryStatus(ref MEMORYSTATUS1 lpBuffer); //获得系统DLL里的函数
            private static Tuple<string, string> QueryCPU()
            {
                Tuple<string, string> result = null;
                try
                {
                    string str = string.Empty;
                    ManagementClass mcCPU = new ManagementClass(WindowsAPIType.Win32_Processor.ToString());
                    ManagementObjectCollection mocCPU = mcCPU.GetInstances();
                    foreach (ManagementObject m in mocCPU)
                    {
                        string name = m[WindowsAPIKeys.Name.ToString()].ToString();
                        string[] parts = name.Split('@');
                        result = new Tuple<string, string>(parts[0].Split('-')[0] + "处理器", parts[1]);
                        break;
                    }

                }
                catch
                {

                }
                return result;
            }
            /// <summary>
            /// 查找cpu的名称，主频, 核心数
            /// </summary>
            /// <returns></returns>
            public static string GetCPU()
            {
                return cpu;
            }
            /// <summary>
            /// 返回内存总大小
            /// </summary>
            /// <returns></returns>
            public static string GetMemorySize()
            {
                return memory;
            }
            /// <summary>
            /// 获取cpu核心数
            /// </summary>
            /// <returns></returns>
            public static string GetCPU_Count()
            {
                string str = "查询失败";
                try
                {
                    int coreCount = 0;
                    foreach (var item in new System.Management.ManagementObjectSearcher("Select * from " +
     WindowsAPIType.Win32_Processor.ToString()).Get())
                    {
                        coreCount += int.Parse(item[WindowsAPIKeys.NumberOfCores.ToString()].ToString());
                    }
                    if (coreCount == 2)
                    {
                        return "双核";
                    }
                    str = coreCount.ToString() + "核";
                }
                catch
                {

                }
                return str;
            }
            /// <summary>
            /// 获取内存信息
            /// </summary>
            /// <returns></returns>
            public static MEMORYSTATUS1 GetISCapacity()
            {
                MEMORYSTATUS1 vBuffer = new MEMORYSTATUS1();//实例化结构
                GlobalMemoryStatus(ref vBuffer);//给此结构赋值
                return vBuffer;
            }
            /// <summary>
            /// 获取系统内存大小
            /// </summary>
            /// <returns>内存大小（单位M）</returns>
            public static string GetPhisicalMemory()
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher();   //用于查询一些如系统信息的管理对象 
                searcher.Query = new SelectQuery(WindowsAPIType.Win32_PhysicalMemory.ToString(), "",
     new string[] { WindowsAPIKeys.Capacity.ToString() });//设置查询条件 
                ManagementObjectCollection collection = searcher.Get();   //获取内存容量 
                ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();

                long capacity = 0;
                while (em.MoveNext())
                {
                    ManagementBaseObject baseObj = em.Current;
                    if (baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value != null)
                    {
                        try
                        {
                            capacity += long.Parse(baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value.ToString());
                        }
                        catch
                        {
                            return "查询失败";
                        }
                    }
                }
                return ToGB((double)capacity, 1024.0);
            }
            /// <summary>
            /// 获取硬盘容量
            /// </summary>
            public static string GetDiskSize()
            {
                string result = string.Empty;
                StringBuilder sb = new StringBuilder();
                try
                {
                    string hdId = string.Empty;
                    ManagementClass hardDisk = new ManagementClass(WindowsAPIType.win32_DiskDrive.ToString());
                    ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                    foreach (ManagementObject m in hardDiskC)
                    {
                        long capacity = Convert.ToInt64(m[WindowsAPIKeys.Size.ToString()].ToString());
                        sb.Append(ToGB(capacity, 1000.0) + "+");
                    }
                    result = sb.ToString().TrimEnd('+');
                }
                catch
                {

                }
                return result;
            }
            /// <summary>
            /// 电脑型号
            /// </summary>
            public static string GetVersion()
            {
                string str = "查询失败";
                try
                {
                    string hdId = string.Empty;
                    ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_ComputerSystemProduct.ToString());
                    ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                    foreach (ManagementObject m in hardDiskC)
                    {
                        str = m[WindowsAPIKeys.Version.ToString()].ToString(); break;
                    }
                }
                catch
                {

                }
                return str;
            }
            /// <summary>
            /// 获取分辨率
            /// </summary>
            public static string GetFenbianlv()
            {
                string result = "1920*1080";
                try
                {
                    string hdId = string.Empty;
                    ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_DesktopMonitor.ToString());
                    ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                    foreach (ManagementObject m in hardDiskC)
                    {
                        result = m[WindowsAPIKeys.ScreenWidth.ToString()].ToString() + "*" +
    m[WindowsAPIKeys.ScreenHeight.ToString()].ToString();
                        break;
                    }
                }
                catch
                {

                }
                return result;
            }
            /// <summary>
            /// 显卡 芯片,显存大小
            /// </summary>
            public static Tuple<string, string> GetVideoController()
            {
                Tuple<string, string> result = null;
                try
                {

                    ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_VideoController.ToString());
                    ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                    foreach (ManagementObject m in hardDiskC)
                    {
                        result = new Tuple<string, string>(m[WindowsAPIKeys.VideoProcessor.ToString()].ToString()
    .Replace("Family", ""), ToGB(Convert.ToInt64(m[WindowsAPIKeys.AdapterRAM.ToString()].ToString()), 1024.0));
                        break;
                    }
                }
                catch
                {

                }
                return result;
            }
            /// <summary>
            /// 操作系统版本
            /// </summary>
            public static string GetOS_Version()
            {
                string str = "Windows 10";
                try
                {
                    string hdId = string.Empty;
                    ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_OperatingSystem.ToString());
                    ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                    foreach (ManagementObject m in hardDiskC)
                    {
                        str = m[WindowsAPIKeys.Name.ToString()].ToString().Split('|')[0].Replace("Microsoft", "");
                        break;
                    }
                }
                catch
                {

                }
                return str;
            }

        }
    }
}
